﻿@inject IHttpService _httpService
@inject NavigationManager NavigationManager

@inject IDataCacheService _dataCacheService
@inject IPopupService PopupService
@inject IUserService _userService



@if (isReady)
{
    @if (PerfectionInfor != null && ShowPerfection)
    {
        <div class="pointer" @onclick="OnClickPerfection">
            <CnGalWebSite.Shared.MasaComponent.PC.Perfections.SingleOverviewCard Model="PerfectionInfor" />
        </div>
        <MDivider Class="w-100 mt-2 mb-2"></MDivider>
    }
    <MButton Text Block Color="secondary" OnClick="OnClickHistory">
        <MIcon Left>mdi-history </MIcon>
        历史编辑记录
    </MButton>
    <AuthorizeView Roles="Admin">
        <Authorized>
            <EditHiddenButton IsHidden="IsHidden" IsHiddenChanged="IsHiddenChanged" Id="Id" Type="Type" />
        </Authorized>
    </AuthorizeView>
    @if (Type == ExaminedNormalListModelType.Entry)
    {
        <AuthorizeView>
            <Authorized>
                @if (isInMonitor)
                {
                    <MButton Text Block Color="secondary" OnClick="@(()=>SetMonitor(false))">
                        <MIcon Left>mdi-monitor</MIcon>
                        已关注
                    </MButton>
                }
                else
                {
                    <MButton Text Block Color="secondary" OnClick="@(()=>SetMonitor(true))">
                        <MIcon Left>mdi-monitor</MIcon>
                        关注词条
                    </MButton>
                }
            </Authorized>
        </AuthorizeView>
    }


    <AuthorizeView>
        <Authorized>
            @foreach (var item in Items)
            {
                <PartNavButton Model="item" />
            }
        </Authorized>
        <NotAuthorized>
            <MButton Text Block Color="primary" OnClick="_userService.Login">
                <MIcon Left>mdi-login </MIcon>
                登入后编辑
            </MButton>
        </NotAuthorized>
    </AuthorizeView>

}
else
{
    <CnGalWebSite.Components.Progressings.ProgressingCard />
}

@code {
    [Parameter]
    public ExaminedNormalListModelType Type { get; set; }
    [Parameter]
    public long Id { get; set; }
    [Parameter]
    public bool ShowPerfection { get; set; }
    [Parameter]
    public string Class { get; set; }
    [Parameter]
    public bool IsEdit { get; set; }
    [Parameter]
    public bool IsHidden { get; set; }
    [Parameter]
    public EventCallback<bool> IsHiddenChanged { get; set; }
    [Parameter]
    public EventCallback<bool> IsEditChanged { get; set; }
    [Parameter]
    public EventCallback<List<ExaminedNormalListModel>> OnClickExamines { get; set; }
    [Parameter]
    public EventCallback<long> OnClickPerfectionInfor { get; set; }

    bool isReady { get; set; }
    bool isInMonitor { get; set; }

    public List<EditButtonLineModel> Items { get; set; } = new List<EditButtonLineModel>();

    public Dictionary<Operation, EditState> EditStates { get; set; } = new Dictionary<Operation, EditState>();

    public List<ExaminedNormalListModel> Examines { get; set; } = new List<ExaminedNormalListModel>();

    public PerfectionInforTipViewModel PerfectionInfor { get; set; } = new PerfectionInforTipViewModel();

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await GetExamineInfor();
        if (Examines.Count != 0)
        {
            ProcButtonList();
            isReady = true;
        }
        StateHasChanged();
    }

    public async Task OnClickHistory()
    {
        await OnClickExamines.InvokeAsync(Examines);
    }

    public async Task OnClickPerfection()
    {
        await OnClickPerfectionInfor.InvokeAsync(PerfectionInfor.Id);
    }


    public void ProcButtonList()
    {
        Items.Clear();
        foreach (var item in EditStates)
        {
            Items.Add(new EditButtonLineModel
            {
                State = item.Value == EditState.Normal ? (Examines.Any(s => s.Operation == item.Key) ? EditState.Normal : EditState.None) : item.Value,
                EditCount = Examines.Count(s => s.Operation == item.Key),
                Id = long.Parse(Examines.FirstOrDefault()?.RelatedId),
                LastEditTime = Examines.Where(s => s.Operation == item.Key).OrderByDescending(s => s.ApplyTime).FirstOrDefault()?.ApplyTime,
                Operation = item.Key,

            });
        }

    }

    public async Task GetExamineInfor()
    {
        var editStates = new Dictionary<Operation, EditState>();
        try
        {
            if (Type == ExaminedNormalListModelType.Entry)
            {

                var model = await _httpService.GetAsync<EditEntryInforBindModel>("api/entries/GetEntryEditInforBindModel/" + Id);

                Examines = model.Examines;

                if (ShowPerfection)
                {
                    PerfectionInfor = model.PerfectionInfor;
                }

                isInMonitor = model.IsInMonitor;

                editStates.Add(Operation.EstablishMain, model.State.MainState);
                editStates.Add(Operation.EstablishAddInfor, model.State.InforState);

                editStates.Add(Operation.EstablishImages, model.State.ImagesState);
                editStates.Add(Operation.EstablishAudio, model.State.AudioState);
                editStates.Add(Operation.EstablishTags, model.State.TagState);
                editStates.Add(Operation.EstablishRelevances, model.State.RelevancesState);
                editStates.Add(Operation.EstablishMainPage, model.State.MainPageState);
                editStates.Add(Operation.EstablishWebsite, model.State.WebsiteState);

            }
            else if (Type == ExaminedNormalListModelType.Article)
            {
                var model = await _httpService.GetAsync<EditArticleInforBindModel>("api/articles/GetArticleEditInforBindModel/" + Id);

                Examines = model.Examines;

                editStates.Add(Operation.EditArticleMain, model.State.MainState);
                editStates.Add(Operation.EditArticleMainPage, model.State.MainPageState);
                editStates.Add(Operation.EditArticleRelevanes, model.State.RelevancesState);

            }
            else if (Type == ExaminedNormalListModelType.Periphery)
            {
                var model = await _httpService.GetAsync<EditPeripheryInforBindModel>("api/Peripheries/GetPeripheryEditInforBindModel/" + Id);

                Examines = model.Examines;

                editStates.Add(Operation.EditPeripheryMain, model.State.MainState);
                editStates.Add(Operation.EditPeripheryImages, model.State.ImagesState);
                editStates.Add(Operation.EditPeripheryRelatedEntries, model.State.RelatedEntriesState);
                editStates.Add(Operation.EditPeripheryRelatedPeripheries, model.State.RelatedPeripheriesState);

            }
            else if (Type == ExaminedNormalListModelType.Tag)
            {
                var model = await _httpService.GetAsync<EditTagInforBindModel>("api/tags/GetTagEditInforBindModel/" + Id);

                Examines = model.Examines;

                editStates.Add(Operation.EditTagMain, model.State.MainState);
                editStates.Add(Operation.EditTagChildEntries, model.State.ChildEntriesState);
                editStates.Add(Operation.EditTagChildTags, model.State.ChildTagsState);

            }
            else if (Type == ExaminedNormalListModelType.Video)
            {
                var model = await _httpService.GetAsync<EditVideoInforBindModel>("api/videos/GetEditInforBindModel/" + Id);

                Examines = model.Examines;

                editStates.Add(Operation.EditVideoMain, model.State.MainState);
                editStates.Add(Operation.EditVideoImages, model.State.ImagesState);
                editStates.Add(Operation.EditVideoRelevanes, model.State.RelevancesState);
                editStates.Add(Operation.EditVideoMainPage, model.State.MainPageState);


            }

            EditStates = editStates;
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "获取" + Type.GetDisplayName() + "编辑信息失败");
            return;
        }

    }

    public async Task SetMonitor(bool open)
    {
        try
        {
            var obj = await _httpService.PostAsync<EditUserMonitorsModel, Result>("api/examines/EditUserMonitors", new EditUserMonitorsModel
            {
                InMonitor = open,
                Ids = new int[] { (int)Id }
            });
            //判断结果
            if (obj.Successful == false)
            {

                await PopupService.ToastErrorAsync("修改监视状态失败", obj.Error);
            }
            else
            {
                isInMonitor = open;
                StateHasChanged();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "修改监视状态失败");
        }
    }


}
